package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 
 * @since 2024-05-27
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Override
    public R<String> submit(Orders orders) {
        //1.获取用户id
        Long userId = BaseContext.get();
        //2.查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = Db.lambdaQuery(ShoppingCart.class)
                .eq(ShoppingCart::getUserId, userId)
                .list();
        //3.判断用户的购物车数据是否为空,为空则返回错误信息"该用户购物车为空"
        if(shoppingCartList ==null || shoppingCartList.size()== 0){
            throw new CustomException("该用户购物车为空");
        }

        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = Db.lambdaQuery(AddressBook.class)
                .eq(AddressBook::getId, addressBookId)
                .one();
        //4.判断用户地址是否为空,为空返回错误信息"用户地址为空"
        if(addressBook ==null){
            throw new CustomException("用户地址为空");
        }
        //5.向订单表插入一条数据
        //5.1遍历订单数据,算出总的金额大小

        long number = IdWorker.getId(); //工具类IdWorker的getId()生成的订单号
        AtomicInteger amount = new AtomicInteger(0); //原子操作,保证金额运算不出错(线程安全)
        //5.2遍历的同时设置订单明细表的信息
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(number);
            orderDetail.setNumber(shoppingCart.getNumber()); //订单或套餐的数量
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setAmount(shoppingCart.getAmount());
            //通过遍历得到总的套餐价格和数量乘积的和
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //6.封装订单信息
        User user = Db.lambdaQuery(User.class).eq(User::getId, userId).one();
        String name = user.getName();
        orders.setUserName(name);
        String phone = addressBook.getPhone(); //下单预留电话
        orders.setPhone(phone);
        orders.setStatus(2);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now()); //下单时间
        orders.setCheckoutTime(LocalDateTime.now()); //结账时间
        orders.setNumber(String.valueOf(number));
        orders.setAddress(
                (addressBook.getProvinceName() == null?"":addressBook.getProvinceName())
                +(addressBook.getCityName() == null?"":addressBook.getCityName())
                +(addressBook.getDistrictName() == null?"":addressBook.getDistrictName())
                +(addressBook.getDetail() == null?"":addressBook.getDetail()));
        orders.setAmount(new BigDecimal(amount.get()));//获取总金额

        //7.存储订单
        this.save(orders);

        //8.存储订单详细表
        Db.saveBatch(orderDetailList);

        //9.删除该用户id下的所有购物车信息
        Db.lambdaUpdate(ShoppingCart.class).eq(ShoppingCart::getUserId,userId).remove();

        return R.success("下单成功");
    }

    @Override
    public R<Page> pageQuery(Integer page, Integer pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        ordersPage.addOrder(new OrderItem("order_time",false));
        Page<Orders> p = page(ordersPage);
        return R.success(p);
    }
}
